package com.android.gui;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.GuessASketch;
import com.android.controller.Controller;
import com.android.networking.connection.Words;


public class CanvasDrawingActivity extends  Activity   {
	private ArrayList<Path> _graphics = new ArrayList<Path>();
	private Paint mPaint;
	private  String clientMessage;
	static ServerSocket providerSocket;
	Socket connection = null;
	static ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	private static TextView serverStatus;
	private static SurfaceView sv;
    static int col = 0xffffffff;
   
    //
    LinearLayout linear, linear1;
    TextView text1,text2,text3,text4,text5;
    TableLayout _table;
    TableRow r1, r2, r3,r4;
   
    Button b1, b2, b3;   
   
    //
	Controller cont = new Controller();
	
	int pathcount = 0;
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		CanvasDrawingActivity obj = new CanvasDrawingActivity();
		_table = new TableLayout(this);
        mPaint = new Paint();   
        r1 = new TableRow(this);
        text1 = new TextView(this);        
        text1.setText("Draw this Word");
        Words.choose_word();
        String word_guess = Words.getGuess_word();
        text2 = new TextView(this);
        text2.setText(word_guess);
   
        r1.addView(text1);
        r1.addView(text2); 
        r2 = new TableRow(this);
        text3 = new TextView(this);
        text3.setText("This is text3!");
        text4 = new TextView(this);
        text4.setText("This text4!");
        r2.addView(text3);
        r2.addView(text4); 
       
        linear = new LinearLayout(this);
        linear.setOrientation(LinearLayout.VERTICAL);
        sv = new SurfaceView(this);
        sv = new DrawingPanel(this);
       
       
        linear.addView(sv,480,600);
       
        r4 = new TableRow(this);
        r4.setOrientation(TableLayout.HORIZONTAL);
        b1 = new Button(this);
        b1.setText("Button1");
        b1.setMinimumWidth(235);
        b2 = new Button(this);
        b2.setText("Button2");
        b2.setMinimumWidth(235);
        b1.setText("Eraser");
        b2.setText("Clear");
       
        r4.addView(b1);
        r4.addView(b2);
       
        _table.addView(r4);
        _table.addView(r1);
        _table.addView(r2);
        _table.addView(linear);
        
       
       
       
        setContentView(_table);
        sv.setDrawingCacheEnabled(true);
                
       //obj.createConnection();
        //if(cont.test()){
	       // setContentView(new DrawingPanel(this));
	        Log.d("Draw","In onCreate");
	        //mPaint = new Paint();
	        mPaint.setDither(true);   
	        mPaint.setColor(0xFFFFFFFF);
	        mPaint.setStyle(Paint.Style.STROKE);
	        mPaint.setStrokeJoin(Paint.Join.ROUND);
	        mPaint.setStrokeCap(Paint.Cap.ROUND);
	        mPaint.setStrokeWidth(3);
	        
	        // Polling thread for correct answer
	        PollingThread poll = new PollingThread(this);
	        Thread t = new Thread(poll);
	        t.start();
        }
		
	//}
	
	protected void onStop(){
		Log.d("Draw:","Bye Bye!!!");
		super.onStop();
	/*	try{
			in.close();
			out.close();
		providerSocket.close();
		}catch(Exception ex){}
   		System.exit(0);*/
	}
	 
	class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback {
		private DrawingThread _thread;
		private Path path;
				
		public DrawingPanel(Context context) {
			super(context);
            getHolder().addCallback(this);
            _thread = new DrawingThread(getHolder(), this);
            Log.d("Draw","In DrawingPanel Constructor");
		}
		
		
        public boolean onTouchEvent(MotionEvent event) {
        	ArrayList<MotionEvent> p = new ArrayList<MotionEvent>();
        	Log.d("Draw","In onTouchEvent");
            synchronized (_thread.getSurfaceHolder()) {
            	if(event.getAction() == MotionEvent.ACTION_DOWN){
            		path = new Path();
            		path.moveTo(event.getX(), event.getY());
            		path.lineTo(event.getX(), event.getY());
            		//p.add(event);
            		            		
            	}else if(event.getAction() == MotionEvent.ACTION_MOVE){
            		path.lineTo(event.getX(), event.getY());
            		//p.add(event);
            		
            	}else if(event.getAction() == MotionEvent.ACTION_UP){
            		path.lineTo(event.getX(), event.getY());
            		//p.add(event);
            		for(int pr=0;pr<p.size();pr++){
            			Log.d("App",p.get(pr).getX()+"  "+p.get(pr).getY());
            		}
            		//event.setAction(MotionEvent.ACTION_CANCEL);
            		//cont.sendMessage(p);
            		//_graphics.add(path);
            	}
            	Log.d("App",event.getX()+"  "+event.getY());
            	p.add(event);
            	cont.sendMessage(p);
            	_graphics.add(path);
            	/*if(event.getAction() == MotionEvent.ACTION_UP){
            		
            		//p.add(event);
            		
            		//cont.sendMessage(p);
					pathcount++;
            	}*//*else{
					pathcount =0;
					cont.sendMessage(p);
				}*/
            	return true;
            }
		}
		
		@Override
        public void onDraw(Canvas canvas) {
			for (Path path : _graphics) {
				//canvas.drawPoint(graphic.x, graphic.y, mPaint);
					canvas.drawPath(path, mPaint);
			}
		}
		
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
								   int height) {
			// TODO Auto-generated method stub
			
		}
		
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			Log.d("Draw","In surfaceCreated");
			_thread.setRunning(true);
            _thread.start();
		}
		
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			Log.d("Draw","In surfaceDestroyed");
			boolean retry = true;
            _thread.setRunning(false);
            while (retry) {
                try {
                    _thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                    // we will try it again and again...
                }
            }
		}
	}
	
	class PollingThread implements Runnable{

		CanvasDrawingActivity obj;
		
		PollingThread(CanvasDrawingActivity obj1)
		{
			obj = obj1;
		}
		
		public void run() {
			// TODO Auto-generated method stub
			//boolean flag = false;
			while(true)
			{				
			if(Words.isIs_answer_correct()==true)
			{
				/*CharSequence text = "Correct Answer";
	            Toast toast = Toast.makeText(obj, text, Toast.LENGTH_LONG);
	        	toast.show();
	        	break;
	        	*/
				break;				
			} else
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//CharSequence text = "Correct Answer";
            //Toast toast = Toast.makeText(obj, text, Toast.LENGTH_LONG);
        	//toast.show();
        	try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Intent myintent = new Intent(CanvasDrawingActivity.this,GuessASketch.class);
			CanvasDrawingActivity.this.startActivity(myintent);
			
		}
		
	}
	
	class DrawingThread extends Thread {
        private SurfaceHolder _surfaceHolder;
        private DrawingPanel _panel;
        private boolean _run = false;
		
        public DrawingThread(SurfaceHolder surfaceHolder, DrawingPanel panel) {
        	Log.d("Draw","In DrawingThread Constructor");
            _surfaceHolder = surfaceHolder;
            _panel = panel;
        }
		
        public void setRunning(boolean run) {
            _run = run;
        }
		
        public SurfaceHolder getSurfaceHolder() {
            return _surfaceHolder;
        }
		
        @Override
        public void run() {
            Canvas c;
            while (_run) {
                c = null;
                try {
                    c = _surfaceHolder.lockCanvas(null);
                    synchronized (_surfaceHolder) {
                        _panel.onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        _surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}
